<template>
  <img ref="authImg" class="token-img">
</template>
<script>
import { getToken } from '@/util/auth'
export default {
  name: 'TokenImg',
  props: {
    imgUrl: {
      type: String,
      required: true,
      default: ''
    }
  },
  watch: {
    imgUrl: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getImgUrl()
        }
      }
    }
  },
  methods: {
    getImgUrl() {
      Object.defineProperty(Image.prototype, 'imgurl', {
        configurable: true,
        writable: true,
        enumerable: true
      })
      const request = new XMLHttpRequest()
      request.responseType = 'blob'
      request.open('get', this.imgUrl, true)
      request.setRequestHeader('Token', getToken())
      request.send()
      request.onreadystatechange = e => {
        if (request.readyState === 4 && request.status === 200) {
          const imgRef = this.$refs.authImg
          imgRef.src = URL.createObjectURL(request.response)
          imgRef.onLoad = () => {
            URL.revokeObjectURL(imgRef.src)
          }
        }
      }
    }
  }
}
</script>
